package com.emm.yixun.website.controller.customer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
//框架包
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.model.enums.MerchantEnum;
import com.emm.yixun.common.model.enums.QuestionnaireTypeNormalEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.common.model.QuestionnaireAnswer;
//变化的引用
import com.emm.yixun.common.model.QuestionnaireModel;
import com.emm.yixun.common.model.QuestionnaireModelInfo;
import com.emm.yixun.common.model.QuestionnaireQuestion;
import com.emm.yixun.common.model.Resources;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.QuestionnaireAnswerDto;
import com.emm.yixun.common.model.dto.QuestionnaireModelDto;
import com.emm.yixun.common.model.dto.QuestionnaireQuestionDto;
import com.emm.yixun.common.model.enums.IsValidEnum;
import com.emm.yixun.common.model.enums.QuestionnaireTypeEnum;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.QuestionnaireAnswerServiceFacade;
import com.emm.yixun.customer.service.QuestionnaireModelServiceFacade;
import com.emm.yixun.customer.service.QuestionnaireQuestionServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.utils.QuestionnaireToWordUtil;
import com.emm.yixun.website.vo.customer.QuestionAndAnswersVo;
import com.emm.yixun.website.vo.customer.QuestionAnswerVo;
import com.emm.yixun.website.vo.customer.QuestionVo;


@Controller
@RequestMapping("/customer/questionnaireModel/")
public class QuestionnaireModelController extends BaseController<QuestionnaireModel>{
	
	@Autowired
	private QuestionnaireModelServiceFacade questionnaireModelServiceFacade;
	@Autowired
	private QuestionnaireQuestionServiceFacade questionnaireQuestionServiceFacade;
	@Autowired
	private QuestionnaireAnswerServiceFacade questionnaireAnswerServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			List<Resources> list = getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
			for(Resources btn : list) {
				String permission = btn.getPermission().replace("questionnaire:model:", "");
				map.put(permission, permission);
			}
			map.put("permitBtn", list);		
			return "/system/questionnaire/model/questionnaireModel_list";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 跳转问卷模板新增页面
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toAdd")
	public String toAdd(ModelMap map, Long modelId){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//获取创建人信息
			User user=ShiroUtil.getCurrentUser();
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取创建时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			
			//获取问卷类型
			if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(user.getMerchantId()))
				|| MerchantEnum.GREEN_TOWN_TEST.getNo().equals(String.valueOf(user.getMerchantId()))){
				map.addAttribute("questionnaireType", QuestionnaireTypeEnum.values());
			}else{
				map.addAttribute("questionnaireType", QuestionnaireTypeNormalEnum.values());
			}

			return "/system/questionnaire/model/questionnaireModel_add";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(QuestionnaireModelDto dto){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:questionnaireModel:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setUserCode(user.getUserCode());
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUser(user.getId());
        		dto.setCreateTime(new Date());
        		dto.setIsValid(IsValidEnum.UNVALID.getNo()); //默认无效（未启用）
        		dto.setDelFlag("0");
				Response<QuestionnaireModelDto> response=questionnaireModelServiceFacade.saveInfo(dto, null);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	//}
    	return ar;
    }
	
	/**
	 * 弹出复制问卷框
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toCopy")
	public String toCopy(Long id, String flag, ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询模板名称及模板描述
			Response<QuestionnaireModel> response=questionnaireModelServiceFacade.findById(id);
			if(response.isSuccess() && response.getEntity() != null){
				map.addAttribute("copyId", id);
				map.addAttribute("name", response.getEntity().getName() + "_副本");
				map.addAttribute("describe", 
						StringUtils.isBlank(response.getEntity().getQuestionnaireDescribe()) ?
								"" : response.getEntity().getQuestionnaireDescribe());
			}
			//获取修改人信息
			User user=ShiroUtil.getCurrentUser();
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取修改时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			//判断是否需要刷新列表
			map.addAttribute("flag", flag);
			
			return "/system/questionnaire/model/questionnaireModel_copy";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 复制问卷模板
	 * @param dto
	 * @param copyId
	 * @return
	 */
	@RequestMapping(value="copy", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes copy(QuestionnaireModelDto dto, long copyId){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:questionnaireModel:edit"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setUserCode(user.getUserCode());
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUser(user.getId());
        		dto.setCreateTime(new Date());
        		dto.setIsValid(IsValidEnum.UNVALID.getNo()); //默认无效（未启用）
        		dto.setDelFlag("0");
				Response<QuestionnaireModelDto> response=questionnaireModelServiceFacade.saveInfo(dto, copyId);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	//}
    	return ar;
    }
	
	/**
	 * 跳转问卷模板预览页面
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toView")
	public String toView(Long modelId, ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			map.addAttribute("modelId", modelId);
			//查询模板名称及模板描述
			Response<QuestionnaireModel> response=questionnaireModelServiceFacade.findById(modelId);
			if(response.isSuccess() && response.getEntity() != null){
				map.addAttribute("name", response.getEntity().getName());
			}
			return "/system/questionnaire/model/questionnaireModel_view";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 问卷预览
	 * @param id
	 * @return
	 */
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:questionnaireModel:view"))){
        	try {
				Response<QuestionnaireModel> response=questionnaireModelServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	/**
	 * 跳转问卷模板编辑页
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toQuestionEdit")
	public String toQuestionEdit(Long modelId, ModelMap map){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			map.addAttribute("modelId", modelId);
			//问卷地址
			String url = "/system/questionnaire/model/question_bank_edit";
			//查询模板名称及模板描述
			Response<QuestionnaireModel> response=questionnaireModelServiceFacade.findById(modelId);
			if(response.isSuccess() && response.getEntity() != null){
				map.addAttribute("name", response.getEntity().getName());
				map.addAttribute("describe", 
						StringUtils.isBlank(response.getEntity().getQuestionnaireDescribe()) ?
								"" : response.getEntity().getQuestionnaireDescribe());
				//问卷类型不等于题库选题时，跳转自定义问卷
				if(QuestionnaireTypeEnum.CUSTIOM.getNo()
				        .equals(response.getEntity().getType())){
				    url = "/system/questionnaire/model/question_edit";
				}
			}
			//获取修改人信息
			User user=ShiroUtil.getCurrentUser();
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取修改时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			
			return url;
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 跳转问卷模板新增页面
	 * @param map
	 * @return
	 */
	@RequestMapping(value="toEdit")
	public String toEdit(ModelMap map, Long modelId, String flag){
		//if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询模板名称、模板描述及是否启用
			String name = "", describe = "", isValid = "";
			if(modelId != null){
				Response<QuestionnaireModel> response=questionnaireModelServiceFacade.findById(modelId);
				if(response.isSuccess() && response.getEntity() != null){
					name = response.getEntity().getName();
					describe = StringUtils.isBlank(response.getEntity().getQuestionnaireDescribe()) ?
									"" : response.getEntity().getQuestionnaireDescribe();
					isValid = response.getEntity().getIsValid();
				}
			}
			map.addAttribute("modelId", modelId);
			map.addAttribute("name", name);
			map.addAttribute("describe", describe);
			map.addAttribute("isValid", isValid);
			//获取创建人信息
			User user=ShiroUtil.getCurrentUser();
			map.addAttribute("userId", user.getId());
			map.addAttribute("userName", user.getUserName());
			//获取创建时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
			map.addAttribute("createTime", sdf.format(Calendar.getInstance().getTime()));
			
			return "/system/questionnaire/model/questionnaireModel_edit";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(QuestionnaireModelDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        //if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:questionnaireModel:edit"))){
        	try {
        		Response<Integer> response=questionnaireModelServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	//}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:questionnaireModel:delete"))){
        	try {
        		Response<Integer> response=questionnaireModelServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(QuestionnaireModelDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
       /* if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:questionnaireModel:list"))){*/
        	try {
        		dto.addDesc("create_time");
				User user = ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		Page<QuestionnaireModelInfo> response = questionnaireModelServiceFacade
        				.findPageInfoByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows()){
                    	response.setRows(new ArrayList<QuestionnaireModelInfo>());
                    }
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	/*}*/
    	return ar;
    }
	
	/**
	 * 导出模板问卷至Word
	 * @param dto
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="exportToWord", method=RequestMethod.GET)
    public void exportToWord(QuestionnaireModelDto dto, HttpServletRequest request, HttpServletResponse response){
    	try{
    		QuestionAndAnswersVo qaaVo = new QuestionAndAnswersVo();
    		long modelId = dto.getId();
    		//问卷信息
    		Response<QuestionnaireModel> qmRes = questionnaireModelServiceFacade.findById(modelId);
    		String title = "";
    		String desc = "";
    		if(qmRes.isSuccess()){
    			QuestionnaireModel qm = qmRes.getEntity();
    			title = qm.getName();
    			desc = qm.getQuestionnaireDescribe();
    			qaaVo.setTitle(title);
    			qaaVo.setDesc(desc);
    		}
    		//问卷题目
    		List<QuestionnaireQuestion> qqList = new ArrayList<QuestionnaireQuestion>();
    		QuestionnaireQuestionDto qqDto = new QuestionnaireQuestionDto();
    		qqDto.setQuestionnaireModelId(modelId);
    		qqDto.setIsValid(IsValidEnum.VALID.getNo());
    		qqDto.setOrders("sort asc");
    		ResponseList<QuestionnaireQuestion> qmResList = questionnaireQuestionServiceFacade.findByDto(qqDto);
    		if(qmResList.isSuccess()){
    			qqList = qmResList.getEntity();
    		}
    		//题目答案
    		List<QuestionnaireAnswer> qaList = new ArrayList<QuestionnaireAnswer>();
    		QuestionnaireAnswerDto qaDto = new QuestionnaireAnswerDto();
    		qaDto.setQuestionnaireId(modelId);
    		qaDto.setIsValid(IsValidEnum.VALID.getNo());
    		qaDto.setOrders("sort asc");
    		ResponseList<QuestionnaireAnswer> qaResList = questionnaireAnswerServiceFacade.findByQuestionnaireId(qaDto);
    		if(qaResList.isSuccess()){
    			qaList = qaResList.getEntity();
    		}
    		if(null != qqList && qqList.size() > 0){
    			List<QuestionVo> questionVoList = new ArrayList<QuestionVo>();
    			for(QuestionnaireQuestion qq: qqList){
    				String questionId = String.valueOf(qq.getId());
    				QuestionVo questionVo = new QuestionVo();
    				questionVo.setId(questionId);
    				questionVo.setQuestion(qq.getQuestion());
    				questionVo.setQuestionDesc(qq.getQuestionnaireDescribe());
    				questionVo.setProblemCode(qq.getProblemCode());
    				questionVo.setAnswerType(qq.getAnswerType());
    				List<QuestionAnswerVo> qaVoList = new ArrayList<QuestionAnswerVo>();
    				if(null != qaList && qaList.size() > 0){
    					for(QuestionnaireAnswer qa: qaList){
    						String qaQuestionId = String.valueOf(qa.getQuestionnaireQuestionId());
    						if(questionId.equals(qaQuestionId)){
    							QuestionAnswerVo qaVo = new QuestionAnswerVo();
        						qaVo.setQuestionId(questionId);
        						qaVo.setAnswer(qq.getAnswerType());
        						qaVo.setAnswer(qa.getAnswer());
        						qaVo.setSort(String.valueOf(qa.getSort()));
        						qaVoList.add(qaVo);
    						}
    					}
    				}
    				//题目选项列表
    				questionVo.setQuestionAnswerList(qaVoList);
    				//题目列表
    				questionVoList.add(questionVo);
    			}
    			qaaVo.setQuestionList(questionVoList);
    		}
    		
    		QuestionnaireToWordUtil.exportWord(qaaVo, response);
    	}catch(Exception ex){
    		ex.printStackTrace();
    		logger.error("导出问卷模板至Word: ", ex);
    	}
    }
}
